//
//  YWCirculationManager.m
//  maintain
//
//  Created by Kyo on 16/6/22.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWCirculationManager.h"
#import "YWCirculationDBManager.h"
#import "WMHttpTool.h"
#import "YWCommonTool.h"
#import "MJExtension.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWMission.h"
#import "YWMissionManager.h"
#import "YWCirculationInfo.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import "YWHandler.h"
#import "YWReportTroubleManager.h"
#import "YWReportTroubleModel.h"
#import "YWTroubleMissionModel.h"
#import "YWTroubleMissionManager.h"
#import "YWEquipmentTroubleRecord.h"
#import "YWEwinManager.h"

@implementation YWCirculationManager
YWSingletonM(Manager)

- (BOOL)updateCirculationInfoWithArray:(NSArray*)circulationInfoArray{
    return [[YWCirculationDBManager shareManager] updateCirculationInfoWithArray:circulationInfoArray];
}

- (void)createAndSaveLocalCirculationInfoWithType:(NSInteger)type troubleId:(NSInteger)troubleId recipient:(YWHandler*)recipient note:(NSString*)note{
    YWCirculationInfo* circulationBill = [[YWCirculationInfo alloc] init];
    circulationBill.infoId = [YWCommonTool negativeTimestampId];
    circulationBill.troubleId = troubleId;
    circulationBill.type = type;
    circulationBill.createTime = [[NSDate date] timeIntervalSince1970]*1000;
    YWHandler *handelr = [[YWHandler alloc] init];
    YWLoginUser *currentUser = [YWLoginTool loginUser];
    handelr.uniqueId = currentUser.uniqueId;
    handelr.userName = currentUser.userName;
    handelr.mobile = currentUser.mobile;
    handelr.headIcon = currentUser.headIcon;
    circulationBill.author = handelr;
    if (recipient) {
        circulationBill.recipient = recipient;
    }
    circulationBill.note = note?:@"";
    circulationBill.isRead = YES;
    [self saveCirculationInfoWithArray:@[circulationBill]];
}

- (BOOL)saveCirculationInfoWithArray:(NSArray*)circulationInfoArray{
    return [[YWCirculationDBManager shareManager]saveCirculationInfoWithArray:circulationInfoArray];
}

- (BOOL)updateReadStatusWithTroubleId:(NSInteger)troubleId{
    return [[YWCirculationDBManager shareManager] updateReadStatusWithTroubleId:troubleId];
}

-(NSInteger)noReadCountWithTroubleId:(NSInteger)troubleId{
    return [[YWCirculationDBManager shareManager] noReadCountWithTroubleId:troubleId];
}

- (NSArray *)circulationInfoArrayWithTroubleId:(NSInteger)troubleId{
    return [[YWCirculationDBManager shareManager] circulationInfoArrayWithTroubleId:troubleId];
}

- (YWCirculationInfo *)circulationInfoWithCirculationType:(NSInteger)type troubleId:(NSInteger)troubleId{
    return [[YWCirculationDBManager shareManager] circulationInfoWithCirculationType:type troubleId:troubleId];
}

-(void)requestCirculationInfoWithTroubleId:(NSInteger)troubleId needTip:(BOOL)needTip WithComplete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    NSString* url = [NSString stringWithFormat:@"%@/%ld", [YWCommonTool getCirculationInfoUrl], (long)troubleId];
    YWLog(@"url:%@",url);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:nil success:^(NSHTTPURLResponse* response, id json) {
        YWReportTroubleModel* reportTrouble = [YWReportTroubleModel mj_objectWithKeyValues:json];

        if (reportTrouble) {
            //更新报障信息，流转和记录会在报障信息里面更新，维修信息也会再里面更新
            [[YWReportTroubleManager shareManager] updateReportTroubleWithArray:@[reportTrouble]];
            //当撤回，退回维修任务，不再返回维修对象时通过一下方法更新维修单状态
            [[YWTroubleMissionManager shareManager] updateTroubleMissionStatus:reportTrouble.troubleStatus troubleId:reportTrouble.troubleId];
            //更新维修信息
//            if (reportTrouble.troubleMission) {
//                [[YWTroubleMissionManager shareManager] updateTroubleMissionWithArray:@[reportTrouble.troubleMission] needUpdateReportTrouble:NO];
//            }
////            //保存流转信息
//            [[YWCirculationManager shareManager] updateCirculationInfoWithArray:troubleMissionJson.circulationInfos];
////            //保存维修记录
//            [[YWMissionManager shareManager] saveTroubleRecordJsons:troubleMissionJson.records];
        }
        
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (needTip) {
            if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
            }else {
                [YWCommonTool showTextHUDWithContent:@"刷新失败,请稍后再试"];
            }
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)requestCirculationInfoOfRecordWithTroubleId:(NSInteger)troubleId WithComplete:(void (^)(YWEquipmentTroubleRecordJson *troubleMissionJson))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(nil);}return;}
    
    NSString* url = [YWCommonTool getTroubleRecordUrl];//[NSString stringWithFormat:@"%@/%ld", [YWCommonTool getTroubleRecordUrl], (long)troubleId];
    NSDictionary *params = @{@"troubleId" : @(troubleId)};
    YWLog(@"url:%@,params:%@",url,params);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray * troubleRecordJson = [YWEquipmentTroubleRecordJson mj_objectArrayWithKeyValuesArray:json];
//        YWTroubleMissionModelJson* troubleMissionJson = [YWTroubleMissionModelJson mj_objectWithKeyValues:json];
//        if (troubleMissionJson) {
//            //保存维修记录
//            [[YWMissionManager shareManager] saveTroubleRecordJsons:troubleMissionJson.records];
//        }
        if (troubleRecordJson.count) {
            [[YWTroubleMissionManager shareManager] saveTroubleRecordJsons:troubleRecordJson];
        }
        if (complete) {
            if (troubleRecordJson.count) {
                complete(troubleRecordJson[0]);
            }else{
                complete(nil);
            }
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(nil);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)cancelPostTroubleWithTroubleId:(NSInteger)troubleId cancelNote:(NSString *)cancelNote WithComplete:(void (^)(NSInteger))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(0);}return;}
    
    NSString* url = [NSString stringWithFormat:@"%@/%ld", [YWCommonTool cancelPostTroubleUrl], (long)troubleId];
    NSDictionary *params = @{@"cancelNote" : cancelNote?:@""};
    [[WMHttpTool shareHttpTool] putWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        //创建保存流转信息
        [[YWCirculationManager shareManager] createAndSaveLocalCirculationInfoWithType:YWCirculationInfoTypeCancelTrouble troubleId:troubleId recipient:nil note:cancelNote];
        //更新报障单状态
        [[YWReportTroubleManager shareManager] updateReportTroubleStatus:YWTroubleMissionStatusCancelPostTrouble troubleId:troubleId];
        //报障单未读数-1
        [[YWEwinManager shareManager] subtractTotalCountWithType:YWUnReadCountTypeTrouble];
        //抢单未读数-1
        [[YWEwinManager shareManager] subtractTotalCountWithType:YWUnReadCountTypeUnDistributionTroubleTotal];
//        YWReportTroubleModel* troubleMissionJson = [YWReportTroubleModel mj_objectWithKeyValues:json];
//        if (troubleMissionJson) {
//            //保存流转信息
//            [[YWCirculationManager shareManager] updateCirculationInfoWithArray:troubleMissionJson.circulationInfos];
//            //更新任务的状态是取消报障
//            [[YWReportTroubleManager shareManager] updateReportTroubleStatus:YWTroubleMissionStatusCancelPostTrouble troubleId:troubleId];
//        }
        if (complete) {
            complete(200);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(response.statusCode);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else if (response.statusCode == 400){
            [YWCommonTool showTextHUDWithContent:@"故障已分配,无法撤回"];
        }else{
            [YWCommonTool showTextHUDWithContent:@"撤回报障失败,请稍后再试"];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}
-(void)cancelTroubleMissionWithTrouble:(YWTroubleMissionModel*)troubleMissionModel WithComplete:(void (^)(NSInteger))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(0);}return;}
    
    NSString* url = [NSString stringWithFormat:@"%@/%ld", [YWCommonTool cancelTroubleMissionUrl], (long)troubleMissionModel.trouble.troubleId];
    [[WMHttpTool shareHttpTool] putWithUrl:url params:nil success:^(NSHTTPURLResponse* response, id json) {
        //创建保存流转信息
        [[YWCirculationManager shareManager] createAndSaveLocalCirculationInfoWithType:YWCirculationInfoTypeCancelTroubleMission troubleId:troubleMissionModel.trouble.troubleId recipient:nil note:nil];
        
        //更新维修单状态
        [[YWTroubleMissionManager shareManager] updateTroubleMissionStatus:YWTroubleMissionStatusUnAssign troubleId:troubleMissionModel.trouble.troubleId];
        //更新报障单状态
        [[YWReportTroubleManager shareManager] updateReportTroubleStatus:YWTroubleMissionStatusUnAssign troubleId:troubleMissionModel.trouble.troubleId];
        //未读数减1（维修）
        [[YWEwinManager shareManager] subtractTotalCountWithType:YWUnReadCountTypeFixTrouble];
        //报障单未读数+1
        [[YWEwinManager shareManager] addTotalCountWithType:YWUnReadCountTypeTrouble];
        //抢单未读数+1
        [[YWEwinManager shareManager] addTotalCountWithType:YWUnReadCountTypeUnDistributionTroubleTotal];
        //返回json是一个{}，全量信息会在流转信息接口返回
        
//        YWTroubleMissionModelJson* troubleMissionJson = [YWTroubleMissionModelJson mj_objectWithKeyValues:json];
//        YWReportTroubleModel * reportTrouble = [YWReportTroubleModel mj_objectWithKeyValues:json];
//        if (reportTrouble) {
            //保存流转信息
//            [[YWCirculationManager shareManager] updateCirculationInfoWithArray:reportTrouble.circulationInfos];
//            troubleMissionModel.troubleStatus = YWTroubleMissionStatusUnAssign;
//            troubleMissionModel.executor = nil;
//            troubleMissionModel.updateTime = [[NSDate date] timeIntervalSince1970];
//            [[YWReportTroubleManager shareManager] updateReportTroubleWithArray:@[reportTrouble]];
            //在控制器里更新了
//            [[YWTroubleMissionManager shareManager] updateTroubleMissionWithArray:troubleMissionModel? @[troubleMissionModel]:nil needUpdateReportTrouble:NO];
//            [[YWMissionManager shareManager] saveMissionWithMissionArray:troubleMission?@[troubleMission]:nil];
//        }
        if (complete) {
            complete(200);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else if (response.statusCode ==400){
            [YWCommonTool showTextHUDWithContent:@"维修任务只能在分配状态下才能由分配人取消"];
        }else{
            [YWCommonTool showTextHUDWithContent:@"撤回维修任务失败,请稍后重试"];
        }
        YWLog(@"%s,%ld,error:%@", __func__, (long)response.statusCode,error.localizedDescription);
        if (complete) {
            complete(response.statusCode);
        }
    }];
}
-(void)rejectTroubleMissionWithTrouble:(YWTroubleMissionModel*)troubleMissionModel rejectReason:(NSString *)rejectReason WithComplete:(void (^)(NSInteger))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(0);}return;}
    
    NSString* url = [NSString stringWithFormat:@"%@/%ld", [YWCommonTool rejectTroubleMissionUrl], (long)troubleMissionModel.trouble.troubleId];
    NSDictionary *params = @{@"rejectReason" : rejectReason?:@""};
    [[WMHttpTool shareHttpTool] putWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        //创建保存流转信息
        [[YWCirculationManager shareManager] createAndSaveLocalCirculationInfoWithType:YWCirculationInfoTypeReturnTroubleMission troubleId:troubleMissionModel.trouble.troubleId recipient:nil note:rejectReason];
        //更新报障单状态
        [[YWReportTroubleManager shareManager] updateReportTroubleStatus:YWTroubleMissionStatusUnAssign troubleId:troubleMissionModel.trouble.troubleId];
        //更新维修单状态
        [[YWTroubleMissionManager shareManager] updateTroubleMissionStatus:YWTroubleMissionStatusUnAssign troubleId:troubleMissionModel.trouble.troubleId];
        //未读数减1
        [[YWEwinManager shareManager] subtractTotalCountWithType:YWUnReadCountTypeFixTrouble];
        //报障单未读数+1
        [[YWEwinManager shareManager] addTotalCountWithType:YWUnReadCountTypeTrouble];
        //抢单未读数+1
        [[YWEwinManager shareManager] addTotalCountWithType:YWUnReadCountTypeUnDistributionTroubleTotal];
//        YWTroubleMissionModelJson* troubleMissionJson = [YWTroubleMissionModelJson mj_objectWithKeyValues:json];
//        if (troubleMissionJson) {
//            //保存流转信息
//            [[YWCirculationManager shareManager] updateCirculationInfoWithArray:troubleMissionJson.circulationInfos];
//            troubleMission.troubleStatus = YWTroubleMissionStatusUnAssign;
//            troubleMission.executor = nil;
//            troubleMission.updateTime = [[NSDate date] timeIntervalSince1970];
//            [[YWMissionManager shareManager] saveMissionWithMissionArray:troubleMission?@[troubleMission]:nil];
//        }
//        YWReportTroubleModel * reportTrouble = [YWReportTroubleModel mj_objectWithKeyValues:json];
//        if (reportTrouble) {
//            [[YWReportTroubleManager shareManager] updateReportTroubleWithArray:@[reportTrouble]];
//            [[YWTroubleMissionManager shareManager] updateTroubleMissionWithArray:troubleMissionModel? @[troubleMissionModel]:nil needUpdateReportTrouble:NO];
//        }
        if (complete) {
            complete(200);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(response.statusCode);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else if (response.statusCode == 400){
            [YWCommonTool showTextHUDWithContent:@"维修任务只能在分配状态下才能由执行人退回"];
        }else{
            [YWCommonTool showTextHUDWithContent:@"退回失败,请稍后重试"];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}
@end
